package com.example.logindb.sevices;

import com.example.logindb.dto.FeedbackDTO;
import com.example.logindb.entity.Feedback;
import com.example.logindb.repository.FeedbackRepository;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;
import org.threeten.bp.OffsetDateTime;
import org.threeten.bp.ZoneOffset;
import org.threeten.bp.format.DateTimeFormatter;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

@Service
public class FeedbackServiceImpl implements FeedbackService {
    private FeedbackRepository feedbackRepository;

    public FeedbackServiceImpl(FeedbackRepository feedbackRepository) {
        this.feedbackRepository = feedbackRepository;
    }

    @Override
    public void save(Feedback feedback) {
        feedbackRepository.save(feedback);
    }

    @Override
    public List<FeedbackDTO> getfeedback1() {

        List<Feedback> feedback = feedbackRepository.findRecentFeedbacks(0);
        return getFeedbackDTOS(feedback);
    }

    @Override
    public List<FeedbackDTO> getfeedback2() {
        List<Feedback> feedback = feedbackRepository.findRecentFeedbacks2(0);
        return getFeedbackDTOS(feedback);
    }

    @NotNull
    private List<FeedbackDTO> getFeedbackDTOS(List<Feedback> feedback) {
        List<FeedbackDTO> feedbackDTOList = new ArrayList<>();
        for(Feedback f:feedback)
        {
            Timestamp a =  f.getTime();
            String formattedTime = formattedTime(a.toString());
            FeedbackDTO feedbackDTO = new FeedbackDTO();
            feedbackDTO.setFid(f.getFid());
            feedbackDTO.setAid(f.getAid());
            feedbackDTO.setUid(f.getUid());
            feedbackDTO.setContent(f.getContent());
            feedbackDTO.setTime(formattedTime);
            feedbackDTO.setStatus(f.getStatus());
            feedbackDTOList.add(feedbackDTO);
        }
        return feedbackDTOList;
    }

    @Override
    public void done(int id) {
        Feedback feedbak = feedbackRepository.findAllByFid(id);
        feedbak.setStatus(1);
        feedbackRepository.save(feedbak);
    }

    @Override
    public  String formattedTime(String time){
        String[] parts = time.split("\\.");
        return parts[0];
    }
}